$(function () {
    var content_ = "";

    var $search = parseSearch(),
        data = {
            'test': {
                detail: '/info/get?id=' + $search.id,
                add: '/info/create',
                update: '/info/update',
                data: [
                    {
                        type: 'select',
                        label: '问题类型',
                        require: true, // 是否必填
                        placeholder: '请选择问题类型',
                        name: 'category',
                        num: 8,
                        labelNum: 2,
                    },
                    {
                        type: 'upload-btn',
                        label: '图片(可选)',
                        require: true, // 是否必填
                        name: 'thumbnail',
                        previewClass: 'preview',
                        value: '',
                        num: 8,
                        labelNum: 2,
                        validate: 'ipt  validate[required]',

                    },
                    {
                        type: 'textarea',
                        label: '问题描述',
                        require: true, // 是否必填
                        placeholder: '请输入问题描述',
                        name: 'summary',
                        value: '',
                        num: 8,
                        labelNum: 2,
                    },
                    {
                        type: 'textarea',
                        label: '答案选项',
                        require: true, // 是否必填
                        placeholder: '请输入答案选项(答案:分值;答案:分值)',
                        name: 'content',
                        value: '',
                        num: 8,
                        labelNum: 2,
                        btn: {
                            num: '9 col-xs-offset-2 ',
                            class_: 'btn-submit ',
                            htmlReturn: '<a href="./index.html?type=test" class="btn-return-list btn btn-default">返回</a>'
                        },
                    },
                    // {
                    //     type: 'text',
                    //     label: '答案',
                    //     require: true, // 是否必填
                    //     placeholder: '请输入答案(多选题答案请用";"分割)',
                    //     name: 'source',
                    //     value: '',
                    //     num: 8,
                    //     labelNum: 2,
                    // },
                    // {
                    //     type: 'textarea',
                    //     label: '分值',
                    //     require: true, // 是否必填
                    //     placeholder: '请输入分值(整数)',
                    //     name: 'read',
                    //     value: '',
                    //     num: 8,
                    //     labelNum: 2,
                    // },

                ],
                reform: function (data) {
                    // data.content = data.profile;
                    data.type1 = '9';//科普内容
                    data.status = '0';
                    return data;
                },
                shown: function () {
                    $('<a href="javascript:void(0);" class="btn btn-danger " style="    margin-top: 10px;">删除图片</a>').insertAfter($('.upload-select'));
                    $('.upload-select').addClass('btn-warning').css({'margin-right': '10px'});
                    onClick($('.btn-danger'), function () {
                        $('.preview').attr('src', '');
                    })
                    onClick($('.upload-select'), function () {
                        upload('测试图片', {w: 400, h: 300, num: 11, labelNum: 1});
                    });

                    if (!!arg.data[3].val) {
                        var contents = arg.data[3].val.split('<>');
                        $('[name=content]').val(contents[0])
                    }
                    [
                        {type: '1', label: '单选题'},
                        {type: '2', label: '多选题'},
                    ].map(function (item) {
                        $('[name=category]').append('<option value="' + item.type + '">' + item.label + '</option>')
                    })
                    $('[name=category]').val(arg.data[0].val || '');
                    //debugger;
                }
            },
        }, arg = '';
    arg = data[$search.type];
    if ($search.id) { // 修改
        arg = data[$search.type];
        $.get(arg.detail, function (res) {
            if (res.code == 200) {
                if (arg.formatArg) {
                    res.data = arg.formatArg(res.data);
                }
                arg.data = arg.data.map(function (item) {
                    if (res.data[item.name]) item.val = res.data[item.name];
                    return item;
                })
                genForm();
            }
        })
    } else {
        genForm();
    }
    function upload(lab, ratio) {
        ratio = ratio || {};
        dialogForm({
            title: '上传' + lab,
            fullScreen: true,
            data: [
                {
                    type: 'upload-dialog',
                    label: lab,
                    require: true, // 是否必填
                    name: 'upload',
                    labelStyle: ratio.style || '',
                    value: '',
                    num: ratio.num || 8,
                    labelNum: ratio.labelNum || 2,
                    validate: 'ipt  validate[required]',
                    btnClass: 'select-file',
                    btn: {
                        class_: '9 col-xs-offset-1'
                    }
                },
            ],
            shown: function (obj) {
                $('.select-file').$upload({
                    w: ratio.w || 185,
                    h: ratio.h || 164,
                    submit: function (path) {
                        closeLayer(obj.index);
                        $('.preview').attr('src', path.path || path);
                    }
                })
            },
            noForm: true,
            submit: function (data) {
            }
        });
    }

    var self = this;

    function genForm() {
        dialogForm({
            eleId: 'form',
            title: '',
            data: arg.data,
            shown: arg.shown || function () {
            },
            submit: function (data) {
                data.thumbnail = $('.preview').attr('src');
                if (data.thumbnail == '/admin/imgs/upload/UPLOAD.png') {
                    data.thumbnail = '';
                }
                var url = arg.add;
                if ($search.id) {
                    data.id = $search.id;
                    url = arg.update;
                }
                if (data.editorValue) {
                    data.profile = data.editorValue
                }
                if (arg.reform) {
                    data = arg.reform(data);
                }
                data.authorId = parent.MANAGER_CURRENT.id;
                var mapType = [], flag = false;
                // data.content.split(':').map(function (item, Idex) {
                //     console.log(item);//
                //     if (!$('.select' + Idex).val().length) {
                //         flag = true;
                //     }
                //     mapType.push($('.select' + Idex).val().join(','));
                // });
                data.content = data.content
                if (flag) {
                    return alert('请设置选项映射类型');
                }
                $.post(url, data, function (res) {
                    if (res.code == 200) {
                        alert('提交成功！');
                        if(!$search.id){
                            $.post('/dataR/add',{
                                type1:$search.drType,
                                targetId:res.data.id,
                                sourceId:$search.sourceId
                            },function(){
                                window.location.href = './index.html?type=' + $search.type+
                                    ($search.sourceId?('&sourceId='+$search.sourceId+'&drType='+$search.drType+'&'):'');
                            })
                        }

                    } else {
                        fnFail(res.error || '操作失败！')
                    }
                });
            }
        }, true);
    }

    /**
     * 富文本编辑器
     * @param id
     */
    function initEditor(id, content, opt) {
        opt = opt || {};
        window.editor = UE.getEditor(id, {
            //工具栏
            toolbars: [[
                'Source',
                'fullscreen', 'undo', 'redo', '|',
                'bold', 'italic', 'underline', 'strikethrough', , 'removeformat', 'formatmatch',
                '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', '|',
                'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'link', 'unlink', '|',
                'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|', 'indent', '|',
                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                'insertframe', '|',
                'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'simpleupload',
                'horizontal', 'insertvideo'
                // ,'preview'
            ]],
            lang: "zh-cn",//字体
            fontfamily: [
                {label: '', name: 'songti', val: '宋体,SimSun'},
                {label: '', name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
                {label: '', name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
                {label: '', name: 'heiti', val: '黑体, SimHei'},
                {label: '', name: 'lishu', val: '隶书, SimLi'},
                {label: '', name: 'andaleMono', val: 'andale mono'},
                {label: '', name: 'arial', val: 'arial, helvetica,sans-serif'},
                {label: '', name: 'arialBlack', val: 'arial black,avant garde'},
                {label: '', name: 'comicSansMs', val: 'comic sans ms'},
                {label: '', name: 'impact', val: 'impact,chicago'},
                {label: '', name: 'timesNewRoman', val: 'times new roman'}
            ],//字号
            'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36],
            enableAutoSave: false,
            autoHeightEnabled: false,
            initialFrameHeight: '400px',
            initialFrameWidth: '100%',
            readonly: false,
            initialFrameHeight: 300,
            whitList: {
                a: ['target', 'href', 'title', 'class', 'style'],
                abbr: ['title', 'class', 'style'],
                address: ['class', 'style'],
                area: ['shape', 'coords', 'href', 'alt'],
                article: [],
                aside: [],
                audio: ['autoplay', 'controls', 'loop', 'preload', 'src', 'class', 'style'],
                b: ['class', 'style'],
                bdi: ['dir'],
                bdo: ['dir'],
                big: [],
                blockquote: ['cite', 'class', 'style'],
                br: [],
                caption: ['class', 'style'],
                center: [],
                cite: [],
                code: ['class', 'style'],
                col: ['align', 'valign', 'span', 'width', 'class', 'style'],
                colgroup: ['align', 'valign', 'span', 'width', 'class', 'style'],
                dd: ['class', 'style'],
                del: ['datetime'],
                details: ['open'],
                div: ['class', 'style'],
                dl: ['class', 'style'],
                dt: ['class', 'style'],
                em: ['class', 'style'],
                font: ['color', 'size', 'face'],
                footer: [],
                h1: ['class', 'style'],
                h2: ['class', 'style'],
                h3: ['class', 'style'],
                h4: ['class', 'style'],
                h5: ['class', 'style'],
                h6: ['class', 'style'],
                header: [],
                hr: [],
                i: ['class', 'style'],
                img: ['src', 'alt', 'title', 'width', 'height', 'id', '_src', '_url', 'loadingclass', 'class', 'data-latex'],
                ins: ['datetime'],
                li: ['class', 'style'],
                mark: [],
                nav: [],
                ol: ['class', 'style'],
                p: ['class', 'style'],
                pre: ['class', 'style'],
                s: [],
                section: [],
                small: [],
                span: ['class', 'style'],
                sub: ['class', 'style'],
                sup: ['class', 'style'],
                strong: ['class', 'style'],
                table: ['width', 'border', 'align', 'valign', 'class', 'style'],
                tbody: ['align', 'valign', 'class', 'style'],
                td: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
                tfoot: ['align', 'valign', 'class', 'style'],
                th: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
                thead: ['align', 'valign', 'class', 'style'],
                tr: ['rowspan', 'align', 'valign', 'class', 'style'],
                tt: [],
                u: [],
                ul: ['class', 'style'],
                video: ['autoplay', 'controls', 'loop', 'preload', 'src', 'height', 'width', 'class', 'style'],
                source: ['src', 'type'],
                // embed:['type','class','pluginspage','src','wdith','height','align','style','wmode','play','autoplay',
                //     'loop','menu','allowsscriptaccess','allowfullscreen','controls','preload'
                // ],
                iframe: ['src', 'class', 'height', 'width', 'max-width', 'max-height', 'align',
                    'frameborder', 'allowfullscreen'
                ]
            }
        });
        window.editor.ready(function (ueditor) {

            if (opt && opt.source) { // 源码模式
                setTimeout(function () {
                    if (window.editor.queryCommandState('source') != 1) {//判断编辑模式状态:0表示【源代码】HTML视图；1是【设计】视图,即可见即所得；-1表示不可用
                        window.editor.execCommand('source'); //切换到【设计】视图
                    }
                }, 500);
            }
            if (content) {
                window.editor.setContent(content);
            }

        });

        window.editor.addListener('contentChange', function (editor_) {
            var self = this;
            content_ = self.getContent();
        });

    }

    /**
     * 代码编辑器
     * @param opt
     */
    function fnCodeMirror(opt) {
        var myTextarea = document.getElementById(opt.eleId);
        window.CodeMirrorEditor = CodeMirror.fromTextArea(myTextarea, {
            mode: "text/javascript",
            theme: "dracula",	//设置主题
            lineNumbers: true,	//显示行号
            lineWrapping: true,	//代码折叠
            //foldGutter: true,
            //fullScreen: true,
            gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
            viewportMargin: Infinity,
            matchBrackets: true,
        });
        if (opt.content) {
            window.CodeMirrorEditor.setValue(opt.content)
        }
    }

});